<template>
  <div class="box">
    <div class="let" :class="{ 'expanded': isExpanded }">
      <el-form :label-position="labelPosition" :model="formLabelAlign">
        <el-form-item label="缴费人员" class="qwe">
          <el-input v-model="formLabelAlign.username" placeholder="请输入缴费人员"></el-input>
        </el-form-item>
        <el-form-item label="缴费名称">
          <el-input v-model="formLabelAlign.payname" placeholder="请输入缴费名称"></el-input>
        </el-form-item>
        <el-form-item label="支付类型">
          <el-select
            v-model="formLabelAlign.costtype"
            clearable
            style="width:100%"
            placeholder="输入支付类型"
          >
            <el-option label="支付宝支付" value="1"></el-option>
            <el-option label="微信支付" value="2"></el-option>
            <el-option label="银联支付" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态">
          <el-select
            v-model="formLabelAlign.coststatus"
            clearable
            style="width:100%"
            placeholder="输入支付状态"
          >
            <el-option label="已支付" value="1"></el-option>
            <el-option label="未支付" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="formLabelAlign.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="缴费金额">
          <el-input v-model="formLabelAlign.paymoney" placeholder="请输入缴费金额"></el-input>
        </el-form-item>
        <!-- 可折叠的缴费优先级 -->
        <el-form-item label="缴费优先级" v-show="isExpanded">
          <el-input v-model="formLabelAlign.paylevel" placeholder="请输入缴费优先级"></el-input>
        </el-form-item>
        <el-row>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="search">立即查询</el-button>
          <el-button type="text" @click="toggleExpand" class="more-btn">
            {{ isExpanded ? '收起' : '更多' }}
            <i
              :class="isExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
            ></i>
          </el-button>
        </el-row>
      </el-form>
    </div>
    <div class="rit">
      <div class="tou">
        <h2>缴费列表</h2>
        <el-button type="primary" icon="el-icon-download" @click="exportAllData">导出</el-button>
      </div>
      <!-- 为表格容器添加固定高度和滚动条 -->
      <div class="table-container"> 
        <div class="table">
          <el-table :data="tableData" border style="width: 100%" ref="multipleTable">
            <el-table-column prop="payname" label="缴费产品" width="180" align="center"></el-table-column>
            <el-table-column prop="username" label="缴费人员" width="120" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.username">{{scope.row.username}}</span>
                <span v-else>暂无</span>
              </template>
            </el-table-column>
            <el-table-column prop="costtype" label="支付类型" width="120" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.costtype === 1">支付宝</span>
                <span v-else-if="scope.row.costtype ===2">微信支付</span>
                <span v-else-if="scope.row.costtype === 3">银联支付</span>
                <span v-else>暂无</span>
              </template>
            </el-table-column>
            <el-table-column prop="paymoney" label="缴费金额" width="120" align="center"></el-table-column>
            <el-table-column prop="paylevel" label="缴费优先级" width="120" align="center"></el-table-column>
            <el-table-column prop="costtime" label="支付时间" align="center" width="180">
              <template slot-scope="scope">
                <el-tooltip
                  v-if="scope.row.costtime"
                  :content="formatDateTime(scope.row.costtime)"
                  placement="top"
                  effect="light"
                  :open-delay="500"
                >
                  <span>{{ formatDateTime(scope.row.costtime) }}</span>
                </el-tooltip>
                <span v-else>暂无</span>
              </template>
            </el-table-column>
            <el-table-column prop="coststatus" label="支付状态" width="120" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.coststatus === 1">已支付</span>
                <span v-else-if="scope.row.coststatus ===2">未支付</span>
                <!-- <span v-else-if="scope.row.coststatus === 3">欠费</span> -->
                <span v-else>暂无</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">查看</el-button>
                <el-button size="mini" @click="exportSingleRow(scope.row)">导出</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          style="margin-top: 20px; text-align: center;"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
// 引入 xlsx 插件
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      tableData: [],
      labelPosition: "top",
      isExpanded: false, // 控制是否展开
      formLabelAlign: {
        username: "", // 缴费人员
        payname: "", // 缴费名称
        costtype: "", // 支付类型
        coststatus: "", // 支付状态
        dateRange: [], // 时间范围
        paymoney: "", // 缴费金额
        paylevel: "" // 缴费优先级
      },
      token: sessionStorage.getItem("token"),
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  created() {
    this.getTableData();
  },
  methods: {
    formatDateTime(cellValue) {
      if (!cellValue) return "";
      let date = new Date(cellValue);
      let year = date.getFullYear();
      let month = String(date.getMonth() + 1).padStart(2, "0");
      let day = String(date.getDate()).padStart(2, "0");
      let hours = String(date.getHours()).padStart(2, "0");
      let minutes = String(date.getMinutes()).padStart(2, "0");
      let seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    getTableData() {
      // 构造查询参数
      const params = {
        currPage: this.pagination.currentPage - 1, // 后端分页从0开始
        pageNum: this.pagination.pageSize
      };

      // 添加表单查询条件
      if (this.formLabelAlign.username) {
        params.username = this.formLabelAlign.username;
      }
      if (this.formLabelAlign.payname) {
        params.payname = this.formLabelAlign.payname;
      }
      if (this.formLabelAlign.costtype) {
        params.costtype = this.formLabelAlign.costtype;
      }
      if (this.formLabelAlign.coststatus) {
        params.coststatus = this.formLabelAlign.coststatus;
      }
      if (this.formLabelAlign.paymoney) {
        params.paymoney = this.formLabelAlign.paymoney;
      }
      if (
        this.formLabelAlign.dateRange &&
        this.formLabelAlign.dateRange.length === 2
      ) {
        params.startDate = this.formatDate(this.formLabelAlign.dateRange[0]);
        params.endDate = this.formatDate(this.formLabelAlign.dateRange[1]);
      }

      this.$axios
        .get("/cost/getPayMessage", { params })
        .then(res => {
          console.log("内容", res);
          if (res.status === 200) {
            this.tableData = res.data.data.list || res.data.data;
            this.pagination.total = res.data.data.total || res.data.total || 0;
          }
        })
        .catch(error => {
          console.error("获取数据失败:", error);
          this.$message.error("获取数据失败");
        });
    },
    // 格式化日期为 YYYY-MM-DD
    formatDate(date) {
      if (!date) return "";
      let d = new Date(date);
      let year = d.getFullYear();
      let month = String(d.getMonth() + 1).padStart(2, "0");
      let day = String(d.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
    },
    resetForm() {
      // 重置表单数据
      this.formLabelAlign = {
        username: "",
        payname: "",
        costtype: "",
        coststatus: "",
        dateRange: [],
        paymoney: "",
        paylevel: ""
      };
      // 重置分页并重新加载数据
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    search() {
      console.log("查询条件:", this.formLabelAlign);
      this.pagination.currentPage = 1; // 查询时重置到第一页
      this.getTableData();
    },
    handleEdit(index, row) {
      console.log("编辑", index, row);
    //   this.$message.info("编辑功能待实现");
      this.$router.push({
        path: "paychild",
        query: { id: row.id }
      });
    },
    handleDelete(index, row) {
      console.log("删除", index, row);

      // 添加二次确认
      this.$confirm("此操作将永久删除该缴费记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 用户确认删除
          this.$axios
            .get("/cost/delCostData", {
              params: {
                id: row.id,
                token: this.token
              }
            })
            .then(res => {
              if (res.status === 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                // 删除成功后重新加载数据
                this.getTableData();
              } else {
                this.$message({
                  type: "error",
                  message: "删除失败!"
                });
              }
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "删除失败!"
              });
            });
        })
        .catch(() => {
          // 用户取消删除
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 导出单行数据
    exportSingleRow(row) {
      // 将单行数据转换为数组格式
      const data = [
        {
          缴费产品: row.payname || "暂无",
          缴费人员: row.username || "暂无",
          支付类型: this.getCostTypeText(row.costtype),
          缴费金额: row.paymoney || "暂无",
          缴费优先级: row.paylevel || "暂无",
          支付时间: row.costtime ? this.formatDateTime(row.costtime) : "暂无",
          支付状态: this.getCostStatusText(row.coststatus)
        }
      ];

      this.exportToExcel(data, "缴费记录_" + (row.username || "未知用户"));
    },

    // 导出所有数据
    exportAllData() {
      // 处理所有表格数据
      if (!this.tableData || this.tableData.length === 0) {
        this.$message.warning("没有数据可以导出");
        return;
      }
      const data = this.tableData.map(item => ({
        缴费产品: item.payname || "暂无",
        缴费人员: item.username || "暂无",
        支付类型: this.getCostTypeText(item.costtype),
        缴费金额: item.paymoney || "暂无",
        缴费优先级: item.paylevel || "暂无",
        支付时间: item.costtime ? this.formatDateTime(item.costtime) : "暂无",
        支付状态: this.getCostStatusText(item.coststatus)
      }));

      this.exportToExcel(data, "缴费记录_all");
    },

    // 获取支付类型文本
    getCostTypeText(type) {
      switch (type) {
        case 1:
          return "支付宝";
        case 2:
          return "微信支付";
        case 3:
          return "银联支付";
        default:
          return "暂无";
      }
    },

    // 获取支付状态文本
    getCostStatusText(status) {
      switch (status) {
        case 1:
          return "已支付";
        case 2:
          return "未支付";
        default:
          return "暂无";
      }
    },

    // 导出到Excel
    exportToExcel(data, filename) {
      // 创建工作簿
      const ws = XLSX.utils.json_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

      // 导出文件
      XLSX.writeFile(wb, filename + ".xlsx");
    },

    // 分页大小改变时触发
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1; // 改变分页大小时回到第一页
      this.getTableData();
    },
    // 当前页改变时触发
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getTableData();
    }
  }
};
</script>

<style scoped>

.tou {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.qwe > label {
  padding: 0;
}

.box {
  display: flex;
}

.let {
  width: 20%;
  height: 640px; /* 固定高度 */
  overflow-y: auto; /* 超出时显示滚动条 */
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-sizing: border-box;
}

/* 展开时仍然保持固定高度，只是内容可滚动 */
.let.expanded {
  height: 640px;
}

.el-row {
  text-align: center;
  margin-top: 20px;
}

.el-row button {
  margin: 0 10px;
  padding: 8px 16px;
  border-radius: 4px;
}

.more-btn {
  display: inline-block;
  margin-left: 10px;
  font-size: 12px;
}

.el-form-item__label {
  padding: 0;
}

.let .el-form--label-top .el-form-item__label {
  padding: 0px !important;
}

.rit {
  flex: 1;
  margin-left: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  height: 600px;
  display: flex;
  flex-direction: column;
}

/* 添加表格容器样式，固定高度并添加滚动条 */
.table-container {
  flex: 1;
  overflow: auto; /* 只在需要时显示滚动条 */
  display: flex;
  flex-direction: column;
}

.table {
  flex: 1;
  overflow: auto; /* 只在需要时显示滚动条 */
}

/* Tooltip样式优化 */
.el-tooltip__popper {
  max-width: 300px;
}
</style>